package com.itcm.purchase.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itcm.purchase.common.R;
import com.itcm.purchase.common.utils.DoubleCalcUtil;
import com.itcm.purchase.common.utils.PageUtil;
import com.itcm.purchase.entity.PurchaseOrder;
import com.itcm.purchase.entity.dto.PageDto;
import com.itcm.purchase.service.PurchaseOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cm_fighting
 * @since 2020-07-28
 */
@RestController
@RequestMapping("/purchase/purchase-order")
@CrossOrigin
@Api(tags = "采购入库单")
public class PurchaseOrderController {
    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @PostMapping("save")
    @ApiOperation(value = "保存入库单")
    public R save(@RequestBody PurchaseOrder purchaseOrder) {
        if (null != purchaseOrder.getSupplierOutNum() && null != purchaseOrder.getRealInNum()) {
//            purchaseOrder.setPoundDiff(Math.abs(purchaseOrder.getSupplierOutNum() - purchaseOrder.getRealInNum()));

            purchaseOrder.setPoundDiff(DoubleCalcUtil.mul(DoubleCalcUtil.sub(purchaseOrder.getRealInNum(), purchaseOrder.getSupplierOutNum()), (double) 1000));

            if (null != purchaseOrder.getPrice()) {
//                purchaseOrder.setTotalAmount(purchaseOrder.getPrice() * purchaseOrder.getSupplierOutNum());
                purchaseOrder.setTotalAmount(DoubleCalcUtil.mul(purchaseOrder.getPrice(), purchaseOrder.getSupplierOutNum()));
            }
        }
        boolean b = purchaseOrderService.saveOrUpdate(purchaseOrder);
        if (b) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @PostMapping("listPage")
    @ApiOperation(value = "分页查询采购入库单信息")
    public R listPage(@RequestBody PageDto page, String orderDate) {
        Page<PurchaseOrder> pageOrder = PageUtil.getPageParam(page, PurchaseOrder.class);
        purchaseOrderService.listPage(pageOrder, orderDate);
        long total = pageOrder.getTotal();
        List<PurchaseOrder> records = pageOrder.getRecords();
        return R.ok().data("total", total).data("items", records);
    }

    @ApiOperation(value = "批量删除")
    @PostMapping(value = "delBatchIds")
    public R delBatchIds(@RequestParam String ids) {
        String[] idstr = ids.split(",");
        for (String s : idstr) {
            purchaseOrderService.removeById(Long.valueOf(s));
        }
        return R.ok();
    }

    @ApiOperation(value = "获取已存在物资名称列表")
    @RequestMapping(value = "listName", method = {RequestMethod.GET, RequestMethod.POST})
    public R getExistsName() {
        List<String> list = purchaseOrderService.listName();
        return R.ok().data("list", list);
    }
}

